Numbers

Python provide following builtins numeric data types:

  • Integer (int): i = 26011950
  • Floating Point real (float): f = 1.2345
  • Complex (complex): c = 2 + 10j

The builtin function int() can be used to convert other types to integer, including base changes.

Example:


In [10]:
# Converting real to integer
print ('int(3.14) =', int(3.14))
print ('int(3.64) =', int(3.64))
print('int("22") =', int("22"))


int(3.14) = 3
int(3.64) = 3
int("22") = 22
print('int("22.0") !=', int("22.0"))
log
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-8e518d0771bb> in <module>()
----> 1 print('int("22.0") !=', int("22.0"))

ValueError: invalid literal for int() with base 10: '22.0'
print("int(3+4j) =", int(3 + 4j))
log
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-6fb3672eabe6> in <module>()
----> 1 print("int(3+4j) =", int(3 + 4j))

TypeError: can't convert complex to int

In [13]:
# Converting integer to real
print ('float(5) =', float(5))


float(5) = 5.0

In [14]:
print('int("22.0") ==', float("22.0"))


int("22.0") == 22.0

In [15]:
print('int(float("22.0")) ==', int(float("22.0")))


int(float("22.0")) == 22

In [16]:
# Calculation between integer and real results in real
print ('5.0 / 2 + 3 = ', 5 / 2 + 3)


5.0 / 2 + 3 =  5.5

In [17]:
x = 3.5
y = 2.5
z = x + y
print(x, y, z)
print(type(x), type(y), type(z))
z = int(z)
print(x, y, z)
print(type(x), y, type(z))


3.5 2.5 6.0
<class 'float'> <class 'float'> <class 'float'>
3.5 2.5 6
<class 'float'> 2.5 <class 'int'>

In [18]:
# Integers in other base
print ("int('20', 8) =", int('20', 8)) # base 8
print ("int('20', 16) =", int('20', 16)) # base 16


int('20', 8) = 16
int('20', 16) = 32

In [19]:
# Operations with complex numbers
c = 3 + 4j
print ('c =', c)

print ('Real Part:', c.real)
print ('Imaginary Part:', c.imag)
print ('Conjugate:', c.conjugate())


c = (3+4j)
Real Part: 3.0
Imaginary Part: 4.0
Conjugate: (3-4j)